import {toRaw} from 'vue';
import type {Ref} from 'vue';
import {Form} from 'ant-design-vue';
const useAntdForm = Form.useForm;
interface Props {
  [key: string]: any;
}
type FormType = {
  formData: Props | Ref<Props>;
  rules: Props | Ref<Props>;
  options?: {
    immediate?: boolean;
    deep?: boolean;
    validateOnRuleChange?: boolean;
    debounce?: any;
  };
  submit?: () => void;
  reset?: () => void;
};

export default function useForm(params: FormType) {
  const {formData, rules, options, submit, reset} = params;

  const {resetFields, validate, clearValidate, validateInfos} = useAntdForm(formData, rules, options);

  const handleSubmit = (): void => {
    validate()
      .then(() => {
        if (submit && typeof submit === 'function') {
          submit();
        }
        console.log(toRaw(formData));
      })
      .catch((err) => {
        console.log('表单验证=> error', err);
      });
  };
  const handleReset = async (): Promise<void> => {
    await resetFields();
    if (reset && typeof reset === 'function') {
      reset();
    }
  };

  return {
    resetFields,
    validate,
    clearValidate,
    validateInfos,
    handleSubmit,
    handleReset,
  };
}
